// var uri = 'http://localhost'
// var uri = 'https://www.ofven.com'
var uri = 'https://survey.utils.win'
let sites = [
    '', '', '', '/signIn',
    '', '', '', '/aboutUs',
    '', '', '', '/contactUs',
    '', '', '', '/privacyPolicy',
    '', '', '', '/termsOfUse',
    '', '', '', '/signUp',
    '', '', ''
];
var countryCode0 = '';
var $newTd = $(
    '<td colspan="6"><div class="d-flex justify-content-center"><div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div></div></dt>'
);
var $newTd2 = $(
    '<td colspan="6"><div class="d-flex justify-content-center">没有题，请先到管理后台拉题</div></dt>'
);

// 生成一个随机索引
function getRandomIndex(array) {
    return Math.floor(Math.random() * sites.length);
}

// 从数组中随机取出一个元素
function getSite(open_urls) {
    const randomIndex = getRandomIndex(sites);
    if (open_urls) {
        return uri + sites[randomIndex] + '?url=' + encodeURIComponent(open_urls);
    } else {
        return uri + sites[randomIndex];
    }
}


$('.pull-survey-btn').on('click', function(e) {
    e.preventDefault(); // 阻止链接默认行为
    pullSurvey()
});
$('.web-pull-btn').on('click', function(e) {
    e.preventDefault(); // 阻止链接默认行为


    var open_urls = uri + "/bitlabs/bitSurveys/pull";
    if (countryCode0) {
        open_urls = uri + "/bitlabs/bitSurveys/pull/" + countryCode0;
    } else {
        alert('请选择国家');
        return;
    }

    $(this).hide();
    $('.cre-all-loading').show();

    setTimeout(() => {
        $('.cre-all-loading').hide();
        $(this).show();
    }, 10000);

    create_open_link(null, countryCode0, null, null, null, getSite(null), open_urls)
});

function pullSurvey() {
    var surveyId = $('input[type="text"][id="input_region"]').val();
    $('#dataTable > tbody').empty();

    // 将结果渲染到页面上，例如使用 JSON.stringify 将结果转换为字符串
    var $table = $('#dataTable > tbody');
    var $row = $('<tr ></tr>');
    $row.append($newTd);
    $table.append($row);

    var data = {
        "countryCode": countryCode0,
        "surveyId": surveyId,
        "pageSize": 100,
        "pageNum": 1
    }
    $.ajax({
        url: uri + '/bitlabs/bitSurveys/getAll',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function(response) {
            console.log('请求成功:', response);
            $('#dataTable > tbody').empty();
            var $table = $('#dataTable > tbody');
            if (response.code == 0 && response.total > 0) {
                $.each(response.rows, function(index, item) {
                    var $row = $('<tr ></tr>');
                    if (item.type == 'start_bonus') {
                        $row = $('<tr style="background-color: #FFF8F0;"></tr>');
                    }

                    $row.append($('<td>-</td>').text(index + 1));

                    $row.append($('<td>-</td>').text(item.surveyId.substring(0, 5) + '***' + item
                        .surveyId.substring(item.surveyId.length - 5)));
                    $row.append($('<td>-</td>').text(item.cpi));
                    $row.append($('<td>-</td>').text(item.loi));
                    if (item.type == 'survey') {
                        $row.append($('<td><a id="a1_' + item.uid + '_' + item.id +
                            '" href="#" style="color:red" class="create_ads_' + item.id +
                            '">启动</a></td>'));
                    } else {
                        $row.append($('<td><a id="a1_' + item.uid + '_' + item.id +
                            '" href="#" style="color:red" class="create_ads_' + item.id +
                            '">上新</a></td>'));
                    }

                    $table.append($row);
                    $('.create_ads_' + item.id).on('click', function(e) {
                        e.preventDefault(); // 阻止链接默认行为
                        var open_urls = uri + "/bitlabs/user/" + item.userId;

                        // 获取当前点击的a标签的ID
                        var currentId = $(this).attr('id');
                        // 清空其他具有相同模式的a标签的内容
                        $('a[id^="a1_' + item.uid + '"]').each(function() {
                            var thisId = $(this).attr('id');
                            if (thisId !== currentId) {
                                $(this).text('');
                            }
                        });

                        create_open_link(item.id, item.countryCode, item.region, item.city,
                            $(this), getSite(open_urls), item.clickUrl)
                    });
                });
            } else {
                var $row = $('<tr ></tr>');
                $row.append($newTd2);
                $table.append($row);
            }
        },
        error: function(xhr, status, error) {
            $('#dataTable > tbody').empty();
            var $table = $('#dataTable > tbody');
            var $row = $('<tr ></tr>');
            $row.append($newTd2);
            $table.append($row);
            // console.error('请求失败:', xhr, status, error);
        }
    });

}

function create_open_link(id, countryCode, region, city, element, open_urls, open_urls2) {

    var selectElement = document.getElementById('huan_jing_zu_id'); // 环境组id
    var selectedOption = selectElement.options[selectElement.selectedIndex];
    var group_id = selectedOption.value;

    if (element) {
        var currentElement = $(element);
        var $tr = currentElement.closest('tr');

        // 保存原始的 td 元素
        var originalTds = $tr.children('td').clone();

        // 将新的 'td' 元素添加到 'tr' 元素中
        $tr.empty();
        $tr.append($newTd);
    }

    const CHAR_SET = "abcdefghijklmnopqrstuvwxyz0123456789";
    RANDOM_STR = ""
    // 循环生成 6 位随机字符串
    for (let i = 0; i < 6; i++) {
        const randomIndex = Math.floor(Math.random() * CHAR_SET.length);
        RANDOM_STR += CHAR_SET[randomIndex];
    }

    proxy_type = "socks5"
    proxy_host = "proxy.ipidea.io"
    proxy_port = 2333

    // if (region) {
    //     region = '-st-' + region.replace(/\s/g, '');
    //     if (city) {
    //         city = '-city-' + city.replace(/\s/g, '');
    //     } else {
    //         city = '';
    //     }
    // } else {
    region = '';
    city = '';
    // }

    if (countryCode == 'mo' || countryCode == 'tw' || countryCode == 'hk' || countryCode == 'cn') {
        proxy_user = `zhiwu0909-zone-custom-region-${countryCode}-session-${RANDOM_STR}-sessTime-120`
    } else {
        proxy_user = `zhiwu0909-zone-custom-region-${countryCode}${region}${city}-session-${RANDOM_STR}-sessTime-120`
    }
    console.log(proxy_user)
    proxy_password = "zhiwu090901"

    var json_data = {
        "open_urls": [open_urls, open_urls2],
        "group_id": group_id,
        "name": id,
        "remark": countryCode,
        "user_proxy_config": {
            "proxy_type": proxy_type,
            "proxy_host": proxy_host,
            "proxy_port": proxy_port,
            "proxy_soft": "other",
            "proxy_user": proxy_user,
            "proxy_password": proxy_password
        },
        "fingerprint_config": {
            "automatic_timezone": "1",
            "webrtc": "proxy",
            "language_switch": "1",
            "screen_resolution": "none",
            "canvas": "1",
            "webgl_image": "1",
            "webgl": "3",
            "audio": "1",
            "media_devices": "1",
            "client_rects": "1",
            "device_name_switch": "1",
            "random_ua": {
                "ua_browser": ["chrome"],
                "ua_system_version": ["Windows 10", "Windows 11"]
            },
            "speech_switch": "1",
            "browser_kernel_config": {
                "version": "ua_auto",
                "type": "chrome"
            },
            "fonts": ["all"]
        }
    }
    create_adspower_net(id, json_data, $tr, originalTds);
}

function create_adspower_net(id, json_data, trElement, originalElement) {
    // trElement.append('准备创建环境...');
    $.ajax({
        url: "http://127.0.0.1:50325/api/v1/user/create",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(json_data), // 假设 rowData 是你想发送的 JSON 数据
        success: function(response) {
            console.log('创建成功:', response);

            if (response && response.code == 0) {
                // trElement.append('环境创建成功...');
                openAdspower(id, response.data.id, trElement, originalElement);
            } else {
                if (trElement) {
                    trElement.empty();
                    if (response.msg == 'No group permissions') {
                        var $error = $(
                            '<td colspan="6"><div class="d-flex justify-content-center">请在右上角选择自己选项</div></dt>'
                        );
                    } else {
                        var $error = $(
                            '<td colspan="6"><div class="d-flex justify-content-center">环境创建失败</div></dt>'
                        );
                    }
                    trElement.append($error);
                }

            }
        },
        error: function(xhr, status, error) {
            console.error('创建失败:', xhr, status, error);
            if (trElement) {
                trElement.empty();
                var $error = $(
                    '<td colspan="6"><div class="d-flex justify-content-center">环境创建失败，请打开指纹浏览器</div></dt>'
                );
                trElement.append($error);
            }
        }
    });
}

function openAdspower(id, user_id, trElement, originalElement) {
    // trElement.append('准备启动环境...');
    // 发送 POST 请求到服务器
    var json_data = {
        "user_ids": [user_id]
    }
    $.ajax({
        url: "http://127.0.0.1:50325/api/v1/browser/start?new_first_tab=1&user_id=" + user_id,
        type: 'GET',
        contentType: 'application/json',
        data: JSON.stringify(json_data), // 假设 rowData 是你想发送的 JSON 数据
        success: function(response) {
            console.log('启动成功:', response);
            if (trElement && response && response.code == 0) {
                selectAdspower(id, user_id, trElement, originalElement)
            } else {
                if (trElement) {
                    trElement.empty();
                    var $error = $(
                        '<td colspan="6"><div class="d-flex justify-content-center">环境启动失败</div></dt>'
                    );
                    trElement.append($error);
                }

            }
        },
        error: function(xhr, status, error) {
            console.error('启动失败:', xhr, status, error);
            if (trElement) {
                trElement.empty();
                var $error = $(
                    '<td colspan="6"><div class="d-flex justify-content-center">环境启动失败</div></dt>'
                );
                trElement.append($error);
            }
        }
    });
}

function selectAdspower(id, user_id, trElement, originalElement) {
    $.ajax({
        url: "http://127.0.0.1:50325/api/v1/user/list?user_id=" + user_id,
        type: 'GET',
        contentType: 'application/json',
        success: function(response) {
            console.log('查询成功:', response);
            if (response && response.code == 0) {

                trElement.empty();
                var firstTd = originalElement.eq(0);
                firstTd.empty();
                firstTd.text(response.data.list[0].serial_number);
                var lastTd = originalElement.filter(':last');
                lastTd.empty();
                lastTd.append('<a href="#" style="color:red;" class="delete_ads_' +
                    id + '">删除</a>');
                trElement.append(originalElement);

                $('.delete_ads_' + id).on('click', function(e) {
                    e.preventDefault(); // 阻止链接默认行为
                    clearAds(id, user_id, $(this))
                });
            }
        },
        error: function(xhr, status, error) {}
    });
}

function deleteById(id) {

    var json_data = {
        "uid": id
    };
    $.ajax({
        url: uri + '/bitlabs/bitSurveys/deleteById',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(json_data),
        success: function(response) {
            console.log('删除数据成功:', response);
        },
        error: function(xhr, status, error) {
            console.error('删除数据失败:', xhr, status, error);
        }
    });
}

function clearAds(id, user_id, element) {

    var currentElement = $(element);
    var $tr = currentElement.closest('tr');

    // 保存原始的 td 元素
    var originalTds = $tr.children('td').clone();

    // 将新的 'td' 元素添加到 'tr' 元素中
    $tr.empty();
    $tr.append($newTd);

    stopAds(user_id, $tr, originalTds);
}


async function stopAds(userId, trElement, originalElement) {
    await new Promise(resolve => setTimeout(resolve, 1100));
    $.ajax({
        url: "http://127.0.0.1:50325/api/v1/browser/stop?user_id=" + userId,
        type: 'GET',
        contentType: 'application/json',
        success: function(response) {
            console.log('关闭成功:', response);
            deleteAds(userId, trElement, originalElement);
        },
        error: function(xhr, status, error) {
            console.error('关闭失败:', xhr, status, error);
            trElement.empty();
            var $error = $(
                '<td colspan="6"><div class="d-flex justify-content-center">删除失败</div></dt>'
            );
            trElement.append($error);
        }
    });
}
async function deleteAds(userId, trElement, originalElement) {
    await new Promise(resolve => setTimeout(resolve, 1100));
    var json_data = {
        "user_ids": [userId]
    };
    console.log(json_data);
    $.ajax({
        url: "http://127.0.0.1:50325/api/v1/user/delete",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(json_data),
        success: function(response) {
            console.log('删除成功:', response);
            trElement.empty();
            var $error = $(
                '<td colspan="6"><div class="d-flex justify-content-center">删除成功</div></dt>'
            );
            trElement.append($error);
        },
        error: function(xhr, status, error) {
            console.error('删除失败:', xhr, status, error);
            trElement.empty();
            var $error = $(
                '<td colspan="6"><div class="d-flex justify-content-center">删除失败</div></dt>'
            );
            trElement.append($error);
        }
    });
}



// 调用函数
$(document).ready(function() {
    // 遍历 countryMap 数组
    var options = '<option text="" value=""> 不限 </option>';
    for (let i = 0; i < countryMap.length; i++) {
        const country = countryMap[i];
        console.log(`国家代码: ${country.code}, 国家名称: ${country.name}`);
        options += '<option text="' + country.code + '" value="' + country.code + '"> ' + country.name + '(' +
            country.code + ') </option>';
    }
    $('#country_code').html(options);

    $('#country_code').on('change', function() {
        // 获取选中的值
        countryCode0 = $(this).val();
    });
});